package com.example.database;


import android.content.Context;
import android.database.Cursor;
import core.model.mail.Message;

import java.util.ArrayList;
import java.util.List;

public class MailFacade {
    private IMailDAO dao;
    private Context context;

    public MailFacade(Context context) {
        this.context = context;
        this.dao = new MailDAO(context);

    }

    public List<Message> loadMessages(List<String> fileIds) {

        String[] convertedFileIds = new String[fileIds.size()];
        convertArguments(fileIds, convertedFileIds);
        String selection = generateQuery(fileIds);

        this.dao = dao.open();
        Cursor cursor = dao.loadMail(selection, convertedFileIds);
        dao.close();

        List<Message> messages = new ArrayList<Message>();

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            String fileId = cursor.getString(IMailDAO.INDEX_FILE_ID);
            Integer turn = cursor.getInt(IMailDAO.INDEX_TURN);
            String from = cursor.getString(IMailDAO.INDEX_FROM);
            String body = cursor.getString(IMailDAO.INDEX_BODY);
            String type = cursor.getString(IMailDAO.INDEX_TYPE);

            Message message = new Message();
            message.setFile(fileId);
            message.setTurn(turn);
            message.setFrom(from);
            message.setBody(body);
            message.setType(Message.MessageType.generateType(type));

            messages.add(message);
            cursor.moveToNext();
        }

        return messages;
    }

    private String generateQuery(List<String> fileIds) {
        StringBuffer selection = new StringBuffer();
        if (fileIds.size() > 0) {
            selection.append("fileId = ?");
        }

        if (fileIds.size() > 1) {
            for (int index = 1; index < fileIds.size(); index++) {
                selection.append(" OR fileId = ?");
            }
        }
        return selection.toString();
    }

    private void convertArguments(List<String> fileIds, String[] convertedFileIds) {
        int index = 0;
        for (String fileId : fileIds) {
            convertedFileIds[index++] = fileId;
        }
    }


    public boolean saveMessage(Message message) {
        this.dao = dao.open();
        boolean result = dao.saveMail(
                message.getFile(),
                message.getTurn(),
                message.getFrom(),
                message.getBody(),
                message.getType().getElementId());
        dao.close();
        return result;
    }
}
